// 数据接口
import axios from 'axios'

import store from "../store";

import router from "../router";

import { Message } from 'element-ui'

const instance = axios.create({
  timeout: 20 * 1000,
  baseURL: '/fileManageApi'
})

instance.interceptors.request.use(config => {
  const token = store.state.token
  token && (config.headers['X-Access-Token'] = token)
  return config;
})

instance.interceptors.response.use(res => {
  return res
}, err => {
  if (err.response) {
    if (err.response.data.message === 'Token失效请重新登录') {
      Message.error('登录过期，请重新登录!!')
      sessionStorage.clear()
      router.replace({
        path: '/login'
      })
      return
    }
    switch (err.response.status) {
      case 500:
        console.log(err.response.data.message)
        Message.error('服务器错误')
        break
      case 404:
        Message.error('网络请求不存在')
        break
      default:
        return err
    }
  }
})

export function request (config) {
  return instance(config)
}